package com.jmga.ecogasfinder.activities.gasstation;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.w3c.dom.DOMException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.jmga.ecogasfinder.R;
import com.jmga.ecogasfinder.providers.GasFinderProvider;
import com.jmga.ecogasfinder.vo.GasStation;

public class GasStationPricesActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		GasStation gasStation = (GasStation) getIntent().getSerializableExtra(GasFinderProvider.KEY_STATION);
		Log.d(getClass().getName(), "GasStationPreciosActivity onCreate: GasStation-data-received " + gasStation);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gas_station_prices_view);
		
		ContentResolver cr = getContentResolver();
		String idOrder = GasFinderProvider.KEY_ID + " ASC";
		
		Cursor cursor = cr.query(GasFinderProvider.CONTENT_URI_GAS_TYPES, null, null, null, idOrder);
		
		if(cursor.getCount() != 0) {
			for(int i=0; cursor.moveToNext(); i++) {
				String id, description, priceValue;
				
				id = cursor.getString(cursor.getColumnIndexOrThrow(GasFinderProvider.KEY_ID));
				description = cursor.getString(cursor.getColumnIndexOrThrow(GasFinderProvider.KEY_DESCRIPTION));
				priceValue = getPriceFromUrl(id, gasStation);
				
				TableLayout pricesTableLayout = (TableLayout) findViewById(R.id.pricesTableLayout);
				
				if(priceValue != null && !priceValue.isEmpty()) {
					Log.d(getClass().getName(), id + " " + description + " " + priceValue);
					
			        TableRow tr = new TableRow(this);
			        tr.setId(Integer.valueOf(id + 100));
			        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));   
	
			        TextView labelPriceDescription = new TextView(this);
			        labelPriceDescription.setId(Integer.valueOf(id + 200));
			        labelPriceDescription.setText(description);
			        tr.addView(labelPriceDescription);
	
			        TextView labelPriceValue = new TextView(this);
			        labelPriceValue.setId(Integer.valueOf(id + 300));
			        labelPriceValue.setText(priceValue + getString(R.string.euroCurrencyLabel));
			        tr.addView(labelPriceValue);
	
			        pricesTableLayout.addView(tr);
				}
				
			}
		}
	}

	private String getPriceFromUrl(String id, GasStation gasStation) {
		String bbox = gasStation.getXCoord() + "," + gasStation.getYCoord() + "," + gasStation.getXCoord() + "," + gasStation.getYCoord();
		String url_feed = getString(R.string.gas_type_price_url_feed);
		url_feed += "&" + getString(R.string.gasTypeParam_feed) +  "=" + id;
		url_feed += "&" + getString(R.string.BBOXParam_feed) +  "=" + bbox;
		url_feed += "&" +  getString(R.string.searchTypeParam_feed) +  "=" + 0;
		
		URL url;
		
		try {
			url = new URL(url_feed);
			URLConnection connection;
			connection = url.openConnection();

			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();

			if (responseCode == HttpURLConnection.HTTP_OK) {
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				factory.setNamespaceAware(true);
		        XmlPullParser xpp = factory.newPullParser();
		        xpp.setInput(httpConnection.getInputStream(), "ISO-8859-1");
		        
		        int eventType = xpp.getEventType();
		        
		        String labelString = null, priceString = null;
		        
	        	while (eventType != XmlPullParser.END_DOCUMENT ){
	                String name = null;
	                switch (eventType){
	                	case XmlPullParser.START_TAG:
	                		name = xpp.getName();
	                		if (name.equalsIgnoreCase("Rotulo")){
	                			labelString = xpp.nextText();
	                		} else if (name.equalsIgnoreCase("Precio")){
	                			priceString = xpp.nextText();
	                		} 
	                		break;
	                	case XmlPullParser.END_TAG:
	                		name = xpp.getName();
	                		if (name.equalsIgnoreCase("elemento")){
	                			if(labelString != null && gasStation.getLabel().equals(labelString)) {
	                				return priceString;
	                			}
	                		}
	                		break;
	                }
	                eventType = xpp.next();
		        }
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DOMException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}

		
		return "";
	}

	@Override
	protected void onDestroy() {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onDestroy()");
		super.onDestroy();
		
	}

	@Override
	protected void onPause() {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onPause()");
		super.onPause();
	}

	@Override
	protected void onRestart() {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onRestart()");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onResume()");
		super.onResume();
	}

	@Override
	protected void onStart() {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onStart()");
		super.onStart();
	}

	@Override
	protected void onStop() {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onStop()");
		super.onStop();
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onRestoreInstanceState()");
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.d(getClass().getName(), "GasStationPricesActivity super.onRestoreInstanceState()");
		super.onSaveInstanceState(outState);
	}
}